<template>
	<view class="hot-page">
		<!-- 1. 顶部导航栏 -->
		<view class="nav-bar">
			<view class="back-btn" @click="$navigateBack()">←</view>
			<view class="nav-title">声绪热榜</view>
			<view class="empty"></view>
		</view>

		<!-- 2. 分类切换（情绪/场景） -->
		<view class="tab-bar">
			<view class="tab-item" :class="activeTab === 0 ? 'tab-active' : ''" @click="activeTab = 0">
				情绪热榜
			</view>
			<view class="tab-item" :class="activeTab === 1 ? 'tab-active' : ''" @click="getpopularAudio">
				场景热榜
			</view>
		</view>

		<!-- 3. 热榜列表区 -->
		<view class="hot-list">
			<!-- 加载中 -->
			<view class="loading" v-if="loading">
				<view class="loading-icon">●</view>
				<view class="loading-text">加载声音列表中...</view>
			</view>

			<!-- 情绪热榜列表 -->
			<view v-else-if="activeTab === 0">
				<view class="sound-item" v-for="(item, idx) in emotionList" :key="item.id">
					<view class="item-rank" :class="{ 'top3-rank': idx < 3 }">{{ idx + 1 }}</view>
					<view class="item-info">
						<image :src="item.coverUrl" class="item-cover"></image>
						<view class="info-text">
							<view class="sound-title">{{ item.title }}</view>
							<view class="sound-meta">
								<view class="sound-tag">{{ item.scene }}</view>
								<view class="sound-count">
									<text class="icon">▶</text> {{ item.playCount }}次
								</view>
							</view>
						</view>
					</view>
					<view class="item-btns">
						<view class="play-btn" @click="togglePlay(item)"
							:class="{ 'pause-btn': currentPlayId === item.id && isPlaying }">
							{{ currentPlayId === item.id && isPlaying ? '■' : '▶' }}
						</view>
						<view class="collect-btn" @click="toggleCollect(item)"
							:class="{ 'collected': isCollected(item.id) }">
							♥
						</view>
					</view>
				</view>
			</view>

			<!-- 场景热榜列表 -->
			<view v-else>
				<view class="sound-item" v-for="(item, idx) in sceneList" :key="item.id">
					<view class="item-rank" :class="{ 'top3-rank': idx < 3 }">{{ idx + 1 }}</view>
					<view class="item-info">
						<image :src="item.coverUrl" class="item-cover"></image>
						<view class="info-text">
							<view class="sound-title">{{ item.title }}</view>
							<view class="sound-meta">
								<view class="sound-tag">{{ item.scene }}</view>
								<view class="sound-count">
									<text class="icon">▶</text> {{ item.playCount }}次
								</view>
							</view>
						</view>
					</view>
					<view class="item-btns">
						<view class="play-btn" @click="togglePlay(item)"
							:class="{ 'pause-btn': currentPlayId === item.id && isPlaying }">
							{{ currentPlayId === item.id && isPlaying ? '■' : '▶' }}
						</view>
						<view class="collect-btn" @click="toggleCollect(item)"
							:class="{ 'collected': isCollected(item.id) }">
							♥
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="audio-progress" v-if="currentPlayId !== -1">
			<view class="progress-bar" :style="{ width: progress + '%' }"></view>
		</view>
	</view>
</template>

<script>
	import {
		getAudioListByMoodId
	} from '../../api/Audio';
	import {
		collectMusic
	} from '../../api/User';
	import {
		getUserAudioCollect
	} from '../../api/UserAudioCollect';
	import {
		getAudioListByPopular
	} from '../../api/Audio';
import { addListeningHistory } from '../../api/listeningHistory';
	export default {
		onLoad() {
			this.getAudioListByPopular();
			this.initAudio();
			this.getUserAudioCollect(); // 页面加载时获取用户所有收藏的音频ID
			setTimeout(() => {
				this.loading = false;
			}, 1200);
		},

		onUnload() {
			if (this.audioContext) {
				this.audioContext.stop();
				this.audioContext.destroy();
				this.audioContext = null;
			}
		},

		data() {
			return {
				activeTab: 0,
				loading: true,
				currentPlayId: -1,
				isPlaying: false,
				collectedIds: [], // 存储用户所有已收藏音频的ID（关键：用数组区分单个音频）
				audioContext: null,
				progress: 0,
				isLoop: true,
				emotionList: [],
				sceneList: [],
				currentAudio: null
			};
		},


		methods: {
			async getUserAudioCollect() {
				const res = await getUserAudioCollect();
				if (res.data && res.data.length) {
					this.collectedIds = res.data
						.filter(item => item.isCancel == 0)
						.map(item => item.audioId);
				}
			},

			isCollected(audioId) {
				// 检查当前音频ID是否在收藏数组中
				return this.collectedIds.includes(audioId);
			},

			getpopularAudio() {
				this.activeTab = 1;
				this.getAudioListByPopular();
			},

			getAudioListByPopular() {
				if (this.activeTab === 0) {
					getAudioListByPopular(1).then(res => {
						if (res.code === 0) {
							this.emotionList = res.data;
						}
					});
				} else {
					getAudioListByPopular(2).then(res => {
						if (res.code === 0) {
							this.sceneList = res.data;
						}
					});
				}
			},

			initAudio() {
				this.audioContext = uni.createInnerAudioContext();
				this.audioContext.loop = this.isLoop;
				this.audioContext.autoplay = false;
				this.audioContext.onPlay(() => {
					this.isPlaying = true;
				});
				this.audioContext.onPause(() => {
					this.isPlaying = false;
				});
				this.audioContext.onTimeUpdate(() => {
					const duration = this.audioContext.duration;
					const currentTime = this.audioContext.currentTime;
					if (duration > 0) {
						this.progress = (currentTime / duration) * 100;
					}
				});
				this.audioContext.onEnded(() => {
					this.isPlaying = false;
				});
				this.audioContext.onError((err) => {
					this.isPlaying = false;
					let errorMsg = "播放失败";
					if (err && err.errMsg) {
						errorMsg += `：${err.errMsg}`;
					}
					uni.showToast({
						title: errorMsg,
						icon: "none",
						duration: 3000
					});
				});
			},

			togglePlay(item) {
			  this.getAudioListByPopular();
			  this.currentAudio = item;
			  const audioUrl = item.audioUrl?.trim() || '';
			  if (!this.audioContext) {
			    this.initAudio();
			    this.audioContext.addEventListener('ended', () => {
			      this.isPlaying = false;
			      this.currentPlayId = null;
			    });
			  }
			  if (!audioUrl) {
			    console.error("音频地址为空");
			    this.isPlaying = false;
			    this.currentPlayId = null;
			    return;
			  }
			  if (this.currentPlayId === item.id && this.isPlaying) {
			    this.audioContext.pause();
			    this.isPlaying = false;
			    return;
			  }
			  async function playAudio() {
			    if (this.currentPlayId !== item.id) {
			      this.audioContext.stop();
			    }
			    this.currentPlayId = item.id;
			    this.audioContext.src = audioUrl;
			    await this.audioContext.play();
			    this.isPlaying = true;
			    console.log("播放成功");
			    const res = await addListeningHistory(item.id);
			    if (res.code === 0) console.log("历史已记录");
			  }
			  playAudio.call(this);
			  
			},

			toggleCollect(item) {
				this.currentAudio = item;
				const audioId = item.id;
				const isCurrentlyCollected = this.isCollected(audioId);
				collectMusic(audioId).then(res => {
					if (res.code === 0) {
						if (isCurrentlyCollected) {
							this.collectedIds = this.collectedIds.filter(id => id !== audioId);
							uni.showToast({
								title: "取消收藏成功",
								icon: "none"
							});
						} else {
							this.collectedIds.push(audioId);
							uni.showToast({
								title: "收藏成功"
							});
						}
					} else {
						uni.showToast({
							title: isCurrentlyCollected ? "取消收藏失败" : "收藏失败",
							icon: "none"
						});
					}
				});
			},
		}
	};
</script>

<style scoped>
	.hot-page {
		background: #f5f7fa;
		min-height: 100vh;
		padding-bottom: 30rpx;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 100rpx;
		background: #fff;
		padding: 0 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.empty {
		width: 36rpx;
	}

	.tab-bar {
		display: flex;
		height: 80rpx;
		background: #fff;
		margin: 15rpx 0;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #666;
		position: relative;
		cursor: pointer;
	}

	.tab-active {
		color: #2d81ff;
		font-weight: 500;
	}

	.tab-active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 70rpx;
		height: 4rpx;
		background: #2d81ff;
		border-radius: 2rpx;
	}

	/* 3. 热榜列表区 */
	.hot-list {
		padding: 0 20rpx;
	}

	/* 加载中样式 */
	.loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 150rpx 0;
	}

	.loading-icon {
		font-size: 40rpx;
		color: #2d81ff;
		animation: spin 1.5s linear infinite;
		margin-bottom: 20rpx;
	}

	.loading-text {
		font-size: 26rpx;
		color: #666;
	}

	/* 加载旋转动画 */
	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	/* 声音列表项（每首占宽90%） */
	.sound-item {
		display: flex;
		align-items: center;
		width: 90%;
		background: #fff;
		border-radius: 20rpx;
		padding: 25rpx 30rpx;
		margin: 0 auto 20rpx;
		box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.06);
		transition: all 0.2s ease;
	}

	/* 列表项hover效果 */
	.sound-item:hover {
		transform: translateY(-3rpx);
		box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.08);
	}

	/* 排名样式 */
	.item-rank {
		width: 50rpx;
		height: 50rpx;
		background: #f2f5f8;
		border-radius: 50%;
		text-align: center;
		line-height: 50rpx;
		font-size: 24rpx;
		color: #666;
		font-weight: 500;
	}

	/* 前三名排名特殊样式 */
	.top3-rank {
		background: #2d81ff;
		color: #fff;
	}

	/* 封面+信息区 */
	.item-info {
		display: flex;
		align-items: center;
		flex: 1;
		margin: 0 25rpx;
	}

	/* 封面图 */
	.item-cover {
		width: 120rpx;
		height: 120rpx;
		border-radius: 16rpx;
		object-fit: cover;
	}

	/* 文字信息 */
	.info-text {
		margin-left: 25rpx;
	}

	.sound-title {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 10rpx;
	}

	/* 标签+播放量 */
	.sound-meta {
		display: flex;
		align-items: center;
		font-size: 22rpx;
		color: #999;
	}

	.sound-tag {
		background: #edf3ff;
		color: #2d81ff;
		padding: 5rpx 18rpx;
		border-radius: 15rpx;
		margin-right: 20rpx;
	}

	.sound-count .icon {
		font-size: 20rpx;
		margin-right: 5rpx;
	}

	/* 功能按钮区（播放+收藏） */
	.item-btns {
		display: flex;
		align-items: center;
		gap: 30rpx;
	}

	/* 播放按钮 */
	.play-btn {
		width: 60rpx;
		height: 60rpx;
		background: #edf3ff;
		color: #2d81ff;
		border-radius: 50%;
		text-align: center;
		line-height: 60rpx;
		font-size: 24rpx;
		cursor: pointer;
	}

	/* 暂停状态按钮 */
	.pause-btn {
		background: #2d81ff;
		color: #fff;
	}

	/* 收藏按钮 */
	.collect-btn {
		font-size: 36rpx;
		color: #ccc;
		cursor: pointer;
		transition: color 0.2s ease;
	}

	/* 已收藏状态 */
	.collected {
		color: #ff4d6d;
	}
</style>